<script setup>
import {onMounted, ref} from 'vue';
import router from "@/router/index.js";
import {queryAppDetailById, updateApp} from "@/api/app.js";
import CoverUploader from '@/components/UploadAppCover.vue';
import {Message} from '@arco-design/web-vue';
import {queryCategoryList} from '@/api/category.js';

const id = ref(0)
const form = ref({
  id: '',
  appName: '',
  appDesc: '',
  appIcon: '',
  categoryId: null,
  appType: null,
  scoringStrategy: null,
})

const editAppFormRef = ref()
const categoryList = ref([])
const formRules = ref({
  appName: [
    {
      required: true,
      message: '请输入应用名称',
      trigger: 'blur'
    },
    {
      match: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,16}$/,
      message: '应用名称必须为1 - 16位中英文数字',
      trigger: 'blur'
    }
  ],
  appDesc: [
    {
      required: true,
      message: '请输入应用描述',
      trigger: 'blur'
    },
    {
      match: /^.{10,200}$/,
      message: '应用描述须为10 - 200字',
      trigger: 'blur'
    }
  ],
  categoryId: [
    {
      required: true,
      message: '请选择分类',
      trigger: 'change'
    }
  ],
  appType: [
    {
      required: true,
      message: '请选择应用类型',
      trigger: 'change'
    }
  ],
  scoringStrategy: [
    {
      required: true,
      message: '请选择评分策略',
      trigger: 'change'
    }
  ]
})

const refUploader = ref(null); // 图片上传组件引用

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await queryCategoryList()
    if (response.data.code === 1) {
      categoryList.value = response.data.data
    }
  } catch (error) {
    console.error('查询分类列表失败:', error)
  }
}

// 获取应用详情
const getAppDetail = () => {
  // 获取路由中的id
  const params = router.currentRoute.value.params
  id.value = params.id
  queryAppDetailById(id.value)
    .then(res => {
      if (res.data.code === 1) {
        const appDetail = res.data.data
        // 填充表单数据
        form.value = {
          id: appDetail.id,
          appName: appDetail.appName,
          appDesc: appDetail.appDesc,
          appIcon: appDetail.appIcon,
          categoryId: appDetail.categoryId,
          appType: appDetail.appType,
          scoringStrategy: appDetail.scoringStrategy
        }
      } else {
        Message.error('获取应用详情失败')
      }
    })
    .catch(error => {
      console.log(error)
      Message.error('获取应用详情失败')
    })
}

// 提交表单
const submitEditForm = () => {
  const uploaderRef = refUploader.value
  // 验证表单
  editAppFormRef.value.validate(async valid => {
    if (!valid) {
      try {
        form.value.appIcon = await uploaderRef.uploadImage()
        // 提交更新
        const res = await updateApp(form.value)
        if (res.data.code === 1) {
          Message.success("应用更新成功")
          await router.push(`/app/${res.data.data}`)
        } else {
          Message.error("应用更新失败")
        }
      } catch (error) {
        console.log(error)
        Message.error("应用更新失败")
      }
    } else {
      console.log('表单校验失败')
    }
  })
}

onMounted(() => {
  fetchCategoryList()
  getAppDetail()
})
</script>

<template>
  <div id="edit-app-page">
    <a-card class="card">
      <div class="edit-form-container">
        <a-form layout="vertical" :model="form" ref="editAppFormRef" :rules="formRules" class="edit-form">
          <a-page-header
            title="编辑应用"
            @back="router.back"
          >
          </a-page-header>
          <div class="tips">
            <p>
              编辑应用信息后，应用将重新进入审核状态。
            </p>
          </div>
          <a-form-item field="appIcon" label="应用封面">
            <CoverUploader ref="refUploader" v-model="form.appIcon"/>
          </a-form-item>
          <a-form-item field="appName" label="应用名称">
            <a-input v-model="form.appName" placeholder="请输入应用名称" />
          </a-form-item>
          <a-form-item field="appDesc" label="应用描述">
            <a-textarea v-model="form.appDesc" placeholder="请输入应用描述" />
          </a-form-item>
          <a-form-item field="categoryId" label="应用分类">
            <a-select v-model="form.categoryId" placeholder="请选择分类">
              <a-option v-for="item in categoryList" :key="item.id" :value="item.id">
                {{ item.categoryName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="appType" label="应用类型" validate-trigger="blur">
            <a-select v-model="form.appType" placeholder="请选择应用类型">
              <a-option :value="0">得分类</a-option>
              <a-option :value="1">测评类</a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="scoringStrategy" label="评分策略" validate-trigger="blur">
            <a-select v-model="form.scoringStrategy" placeholder="请选择评分策略">
              <a-option :value="0">自定义</a-option>
              <a-option :value="1">AI</a-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" long @click="submitEditForm">编辑应用</a-button>
          </a-form-item>
        </a-form>
      </div>
    </a-card>
  </div>
</template>

<style scoped>
.card {
  margin-top: 20px;
}

.edit-form-container {
  display: flex;
  justify-content: center;
}

.title {
  color: var(--color-text-1);
  margin-bottom: 10px;
}

.tips p{
  color: var(--color-text-2);
  margin-bottom: 5px;
}

.edit-form {
  width: 60%;
}

:deep(.arco-page-header-wrapper) {
  padding: 0;
}

@media (max-width: 768px) {
  .edit-form {
    width: 90%;
  }
}
</style>
